import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {useForm} from 'antd/es/form/Form';
import 'moment/locale/zh-cn';
import request from '../../utils/request';
import API from '../../utils/api';
import FormSearch from './component/FormSearch';
import './index.less';
import classNames from 'classnames';
import {Col, Form, List, Modal, Row, Skeleton} from 'antd';
import Item from '@/pages/history/component/Item';
import PerfectScrollbar from 'perfect-scrollbar';
import 'perfect-scrollbar/css/perfect-scrollbar.css';
import moment from 'moment';
import {get} from "lodash";
import {PaginationConfig} from "antd/es/pagination";
import {downloadFile} from "@/utils/utils";

/**
 * 等待上传文件（刚从3.0系统拉取到数据）, 等待审核（已上传文件，完成房管局填报），错误（数据填报错误）,
 * 已审核(等待比较确认)， 已确认。
 */
export const states: Record<string, string> = {
    waitUpload: '等待上传扫描件',
    waitApprove: '等待审核',
    approved: '已审核',
    confirmed: '已确认',
    waitCompleted: '等待完成',
    completed: '完成',
    error: '错误',
    waitCompleteHouse: '等待填报不动产系统',
    waitCompleteBank: '等待填报3.0系统',
};

export type IHistoryData = {
    id: string;
    contractId: string;
    customName: string;
    contractNo: string;
    createTime: string;
    state: string;
    description: string;
    pledge: string;
    file?: string;
    fileName?: string;
    checked: boolean,
    errorMsg: string;
};

const History: React.FC = () => {
    const [form] = useForm();
    const containerRef = useRef<HTMLDivElement>(null);
    const [loading, setLoading] = useState(false);
    const [autoUpdating, setAutoUpdating] = useState<NodeJS.Timeout | undefined>();
    const [activeState, setActiveState] = useState<string | undefined>();
    const [dataSource, setDataSource] = useState<IHistoryData[]>([]);
    const [pagination, setPagination] = useState<PaginationConfig>({pageSize: 10, current: 1, total: 0})

    const [approveIdList, setApproveIdList] = useState<string[]>([]);
    const [confirmIdList, setConfirmIdList] = useState<string[]>([]);
    const [approveList, setApproveList] = useState<any[]>([]);
    const [approveVisible, setApproveVisible] = useState(false);
    const [approveLoading, setApproveLoading] = useState(false);

    const [statesData, setStateData] = useState(() =>
        Object.keys(states)
            .filter(key => !key.includes('waitComplete') || key === 'waitCompleted')
            .map((s) => ({key: s, name: states[s], amount: 0})),
    );

    const search = useCallback((page: number | undefined = 1, size: number | undefined = pagination.pageSize) => {
        const values = {...form.getFieldsValue()} || {};
        if (values.createTime && Array.isArray(values.createTime)) {
            [values.startDate, values.endDate] = values.createTime.map(
                (i: moment.MomentInput, inx: number) => {
                    if (i) {
                        if (inx === 0) {
                            return moment(i).format('YYYY-MM-DD 00:00:00');
                        }
                        return moment(i).format('YYYY-MM-DD 23:59:59');
                    }
                    return null;
                },
            );
        }
        setLoading(true);
        Promise.all([
            request(API.QUERY_HISTORY, {
                data: {...values, state: activeState, current: page, pageSize: size},
                method: 'POST'
            }),
            request(API.STATISTIC_HISTORY, {data: values, method: 'POST'}),
        ])
            .then(([res, res1]) => {
                setApproveIdList([]);
                setConfirmIdList([]);
                const {data: data1 = []} = res1;
                if (data1 && data1.length) {
                    setStateData(
                        statesData.map((item) => {
                            const dItem = data1.find(
                                (d: { state: string }) => d.state === item.key,
                            );
                            if (dItem) {
                                return {...item, amount: dItem.amount};
                            }
                            return {...item, amount: 0};
                        }),
                    );
                } else {
                    setStateData(statesData.map((i) => ({...i, amount: 0})));
                }
                const {data: {data, current, pageSize, total}} = res;
                setDataSource(data);
                setPagination({current, pageSize, total})
            })
            .finally(() => {
                setLoading(false);
            });
    }, [form, statesData, activeState, pagination]);

    // eslint-disable-next-line react-hooks/exhaustive-deps
    useEffect(() => search(), [activeState]);

    useEffect(() => {
        return () => {
            if (autoUpdating) {
                clearInterval(autoUpdating);
            }
        };
    }, [autoUpdating]);

    const clearAll = useCallback(() => {
        form.resetFields();
    }, [form]);

    const autoUpdate = useCallback(
        (update) => {
            if (update) {
                const inter = setInterval(() => {
                    search();
                }, 6000);
                setAutoUpdating(inter);
            } else if (autoUpdating) {
                clearInterval(autoUpdating);
                setAutoUpdating(undefined);
            }
        },
        [autoUpdating, search],
    );

    const onChangeState = useCallback(
        (event: React.MouseEvent<HTMLDivElement>) => {
            const {currentTarget} = event;
            if (currentTarget.id && currentTarget.id === activeState) {
                setActiveState(undefined);
            } else {
                setActiveState(currentTarget.id);
            }
        },
        [activeState],
    );

    const ps = useMemo(() => {
        if (containerRef && containerRef.current) {
            return new PerfectScrollbar(containerRef.current);
        }
        return null;
    }, [containerRef, containerRef.current]);

    useEffect(() => {
        if (ps) {
            setTimeout(() => {
                ps.update();
            }, 500);
        }
    }, [ps, dataSource.length]);

    // 填写3.0系统相关
    const downloadApprove = useCallback((filename: string) => {
        const url = `http://127.0.0.1:5000file/downloadApprove?id=${filename}`
        request(url, {method: 'get'}).then(res => {
            downloadFile(filename, res.data)
        })
        return false;
    }, []);

    const showApproveDetail = useCallback(() => {
        setApproveLoading(true);
        setApproveVisible(true);
        request(API.APPROVE_DETAIL, {data: {approveIdList, confirmIdList}, method: 'POST'}).then(res => {
            const {data} = res;
            setApproveList(data)
        }).catch(() => {
            setApproveVisible(false)
        }).finally(() => {
            setApproveLoading(false)
        })
    }, [approveIdList, confirmIdList]);

    const handleApprove = useCallback(() => {
        request(API.HOUSE_COMMIT_TO_BANK, {data: {approveIdList, confirmIdList}, method: 'POST'}).then(res => {
            setApproveVisible(false);
        });
    }, [approveIdList, confirmIdList]);

    const handleCheck = useCallback((id: string, checked: boolean) => {
        if (checked) {
            approveIdList.push(id)
        } else {
            approveIdList.forEach((i, inx) => {
                if (i === id) {
                    approveIdList.splice(inx, 1)
                }
            })
        }
        setApproveIdList([...approveIdList])
    }, [approveIdList]);

    const handleConfirmCheck = useCallback((id: string, checked: boolean) => {
        if (checked) {
            confirmIdList.push(id)
        } else {
            confirmIdList.forEach((i, inx) => {
                if (i === id) {
                    confirmIdList.splice(inx, 1)
                }
            })
        }
        setConfirmIdList([...confirmIdList])
    }, [confirmIdList]);

    const handleCheckAll = useCallback((all: boolean) => {
        if (all) {
            const aids: string[] = [];
            const cids: string[] = []
            dataSource.forEach(item => {
                if (item.state == 'confirmed') {
                    cids.push(item.id)
                } else if (item.state == 'approved') {
                    aids.push(item.id)
                }
            });
            setApproveIdList(aids);
            setConfirmIdList(cids);
            return
        }
        setApproveIdList([]);
        setConfirmIdList([]);
    }, [dataSource]);

    return (
        <div id="history" className="history">
            <FormSearch
                clearAll={clearAll}
                form={form}
                loading={loading}
                search={search}
                autoUpdating={!!autoUpdating}
                autoUpdate={autoUpdate}
                checkedIdList={[...approveIdList, ...confirmIdList]}
                showApproveDetail={showApproveDetail}
                checkAll={handleCheckAll}
            />
            <div className="app-list">
                <div>
                    {statesData.map((item) => (
                        <div
                            id={item.key}
                            onClick={onChangeState}
                            key={item.key}
                            className={classNames('app-labels', {
                                'app-labels-active': activeState === item.key,
                            })}
                        >
                            <span>{`${item.name} (${item.amount})`}</span>
                        </div>
                    ))}
                </div>
                <div ref={containerRef} className="list-container">
                    <List
                        pagination={{
                            ...pagination,
                            showSizeChanger: true,
                            onChange: (page, size) => {
                                search(page, size);
                            },
                        }}
                        size="large"
                        dataSource={loading ? ([{}, {}, {}] as IHistoryData[]) : dataSource}
                        renderItem={(item) => (
                            <Item
                                onCheck={handleCheck}
                                checkedList={approveIdList}
                                onConfirmCheck={handleConfirmCheck}
                                confirmIdList={confirmIdList}
                                freshData={search}
                                loading={loading}
                                {...item}
                                key={item.id}
                            />
                        )}
                    />
                </div>
            </div>

            <Modal
                title='他项证明详情'
                onCancel={() => setApproveVisible(false)}
                okText='直接提交'
                onOk={handleApprove}
                width={800}
                closable={false}
                maskClosable={false}
                destroyOnClose
                visible={approveVisible}
            >
                <Skeleton active loading={approveLoading}>
                    {approveList.map((data: any) => (
                        <Form key={data.id}>
                            <Row style={{fontSize: '24px'}}>
                                {data.customName}:
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item label='权证类型'>
                                        {get(data, 'qzType')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='权证编号'>
                                        {get(data, 'qzNo')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记机构类型'>
                                        {get(data, 'djApartmentType')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记机构名称'>
                                        {get(data, 'djApartment')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记金额'>
                                        {get(data, 'djAmt')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记日期'>
                                        {get(data, 'djStartDate')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记日期是否存在到日期'>
                                        {get(data, 'hasEnd') === '1' ? '是' : '否'}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='登记到期日期'>
                                        {get(data, 'djEndDate')}
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='权证类别'>
                                        电子凭证
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item label='证书附件'>
                                        <a onClick={() => downloadApprove(get(data, 'file'))}>{get(data, 'file')}</a>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    ))}
                </Skeleton>
            </Modal>
        </div>
    );
};

export default History;
